#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <memory>
#include <vector>
#include <string>
#include <map>
#include <queue>
#include <algorithm>
#include <numeric>
#include <chrono>

/**
 * 撮合引擎综合测试类
 * 测试订单撮合、价格匹配、交易执行等核心功能
 */
class MatchEngineComprehensiveTest : public ::testing::Test {
protected:
    void SetUp() override {
        // 测试环境初始化
        order_id_counter_ = 1;
        trade_id_counter_ = 1;
        total_volume_ = 0;
        total_amount_ = 0.0;
    }

    void TearDown() override {
        // 测试环境清理
    }

    uint64_t order_id_counter_;
    uint64_t trade_id_counter_;
    uint64_t total_volume_;
    double total_amount_;
};

/**
 * 订单结构体
 */
struct Order {
    uint64_t order_id;
    std::string symbol;
    char side;  // 'B' for buy, 'S' for sell
    double price;
    uint64_t quantity;
    uint64_t filled_quantity;
    std::string order_type;  // "LIMIT", "MARKET"
    uint64_t timestamp;
    
    // 默认构造函数
    Order() : order_id(0), symbol(""), side('B'), price(0.0), quantity(0), filled_quantity(0), order_type("LIMIT"), timestamp(0) {}
    
    Order(uint64_t id, const std::string& sym, char s, double p, uint64_t q, const std::string& type = "LIMIT")
        : order_id(id), symbol(sym), side(s), price(p), quantity(q), filled_quantity(0), order_type(type) {
        timestamp = std::chrono::duration_cast<std::chrono::milliseconds>(
            std::chrono::system_clock::now().time_since_epoch()).count();
    }
    
    bool is_fully_filled() const {
        return filled_quantity >= quantity;
    }
    
    uint64_t remaining_quantity() const {
        return quantity - filled_quantity;
    }
};

/**
 * 成交记录结构体
 */
struct Trade {
    uint64_t trade_id;
    uint64_t buy_order_id;
    uint64_t sell_order_id;
    std::string symbol;
    double price;
    uint64_t quantity;
    uint64_t timestamp;
    
    Trade(uint64_t id, uint64_t buy_id, uint64_t sell_id, const std::string& sym, double p, uint64_t q)
        : trade_id(id), buy_order_id(buy_id), sell_order_id(sell_id), symbol(sym), price(p), quantity(q) {
        timestamp = std::chrono::duration_cast<std::chrono::milliseconds>(
            std::chrono::system_clock::now().time_since_epoch()).count();
    }
};

/**
 * 简单的撮合引擎实现用于测试
 */
class SimpleMatchEngine {
public:
    SimpleMatchEngine() = default;
    
    // 添加订单
    bool add_order(const Order& order) {
        if (order.symbol.empty() || order.quantity == 0) {
            return false;
        }
        
        orders_[order.order_id] = order;
        
        if (order.side == 'B') {
            buy_orders_[order.symbol].push_back(order.order_id);
            // 按价格降序排序（买单价格高的优先）
            std::sort(buy_orders_[order.symbol].begin(), buy_orders_[order.symbol].end(),
                [this](uint64_t a, uint64_t b) {
                    return orders_[a].price > orders_[b].price;
                });
        } else if (order.side == 'S') {
            sell_orders_[order.symbol].push_back(order.order_id);
            // 按价格升序排序（卖单价格低的优先）
            std::sort(sell_orders_[order.symbol].begin(), sell_orders_[order.symbol].end(),
                [this](uint64_t a, uint64_t b) {
                    return orders_[a].price < orders_[b].price;
                });
        }
        
        // 尝试撮合
        match_orders(order.symbol);
        
        return true;
    }
    
    // 取消订单
    bool cancel_order(uint64_t order_id) {
        auto it = orders_.find(order_id);
        if (it == orders_.end()) {
            return false;
        }
        
        const Order& order = it->second;
        
        // 从订单簿中移除
        if (order.side == 'B') {
            auto& buy_list = buy_orders_[order.symbol];
            buy_list.erase(std::remove(buy_list.begin(), buy_list.end(), order_id), buy_list.end());
        } else if (order.side == 'S') {
            auto& sell_list = sell_orders_[order.symbol];
            sell_list.erase(std::remove(sell_list.begin(), sell_list.end(), order_id), sell_list.end());
        }
        
        orders_.erase(it);
        return true;
    }
    
    // 获取订单
    const Order* get_order(uint64_t order_id) const {
        auto it = orders_.find(order_id);
        return (it != orders_.end()) ? &it->second : nullptr;
    }
    
    // 获取所有成交记录
    const std::vector<Trade>& get_trades() const {
        return trades_;
    }
    
    // 获取买单数量
    size_t get_buy_orders_count(const std::string& symbol) const {
        auto it = buy_orders_.find(symbol);
        return (it != buy_orders_.end()) ? it->second.size() : 0;
    }
    
    // 获取卖单数量
    size_t get_sell_orders_count(const std::string& symbol) const {
        auto it = sell_orders_.find(symbol);
        return (it != sell_orders_.end()) ? it->second.size() : 0;
    }
    
    // 获取最佳买价
    double get_best_bid(const std::string& symbol) const {
        auto it = buy_orders_.find(symbol);
        if (it == buy_orders_.end() || it->second.empty()) {
            return 0.0;
        }
        
        uint64_t best_order_id = it->second.front();
        auto order_it = orders_.find(best_order_id);
        return (order_it != orders_.end()) ? order_it->second.price : 0.0;
    }
    
    // 获取最佳卖价
    double get_best_ask(const std::string& symbol) const {
        auto it = sell_orders_.find(symbol);
        if (it == sell_orders_.end() || it->second.empty()) {
            return 0.0;
        }
        
        uint64_t best_order_id = it->second.front();
        auto order_it = orders_.find(best_order_id);
        return (order_it != orders_.end()) ? order_it->second.price : 0.0;
    }
    
    // 获取买卖价差
    double get_spread(const std::string& symbol) const {
        double bid = get_best_bid(symbol);
        double ask = get_best_ask(symbol);
        return (bid > 0 && ask > 0) ? (ask - bid) : 0.0;
    }
    
    // 清空所有数据
    void clear() {
        orders_.clear();
        buy_orders_.clear();
        sell_orders_.clear();
        trades_.clear();
    }

private:
    // 撮合订单
    void match_orders(const std::string& symbol) {
        auto buy_it = buy_orders_.find(symbol);
        auto sell_it = sell_orders_.find(symbol);
        
        if (buy_it == buy_orders_.end() || sell_it == sell_orders_.end()) {
            return;
        }
        
        auto& buy_list = buy_it->second;
        auto& sell_list = sell_it->second;
        
        while (!buy_list.empty() && !sell_list.empty()) {
            uint64_t buy_order_id = buy_list.front();
            uint64_t sell_order_id = sell_list.front();
            
            Order& buy_order = orders_[buy_order_id];
            Order& sell_order = orders_[sell_order_id];
            
            // 检查价格是否匹配
            if (buy_order.price < sell_order.price) {
                break;  // 无法撮合
            }
            
            // 计算成交数量
            uint64_t trade_quantity = std::min(buy_order.remaining_quantity(), sell_order.remaining_quantity());
            double trade_price = sell_order.price;  // 使用卖单价格
            
            // 创建成交记录
            trades_.emplace_back(trades_.size() + 1, buy_order_id, sell_order_id, symbol, trade_price, trade_quantity);
            
            // 更新订单状态
            buy_order.filled_quantity += trade_quantity;
            sell_order.filled_quantity += trade_quantity;
            
            // 移除已完全成交的订单
            if (buy_order.is_fully_filled()) {
                buy_list.erase(buy_list.begin());
            }
            if (sell_order.is_fully_filled()) {
                sell_list.erase(sell_list.begin());
            }
        }
    }
    
    std::map<uint64_t, Order> orders_;
    std::map<std::string, std::vector<uint64_t>> buy_orders_;
    std::map<std::string, std::vector<uint64_t>> sell_orders_;
    std::vector<Trade> trades_;
};

/**
 * 测试基本订单添加功能
 */
TEST_F(MatchEngineComprehensiveTest, TestBasicOrderAddition) {
    SimpleMatchEngine engine;
    
    // 添加买单
    Order buy_order(1, "AAPL", 'B', 150.0, 100);
    EXPECT_TRUE(engine.add_order(buy_order));
    
    // 验证订单被正确添加
    const Order* retrieved_order = engine.get_order(1);
    ASSERT_NE(retrieved_order, nullptr);
    EXPECT_EQ(retrieved_order->order_id, 1);
    EXPECT_EQ(retrieved_order->symbol, "AAPL");
    EXPECT_EQ(retrieved_order->side, 'B');
    EXPECT_EQ(retrieved_order->price, 150.0);
    EXPECT_EQ(retrieved_order->quantity, 100);
    
    // 验证订单簿状态
    EXPECT_EQ(engine.get_buy_orders_count("AAPL"), 1);
    EXPECT_EQ(engine.get_sell_orders_count("AAPL"), 0);
    EXPECT_EQ(engine.get_best_bid("AAPL"), 150.0);
    EXPECT_EQ(engine.get_best_ask("AAPL"), 0.0);
}

/**
 * 测试订单撮合功能
 */
TEST_F(MatchEngineComprehensiveTest, TestOrderMatching) {
    SimpleMatchEngine engine;
    
    // 添加买单
    Order buy_order(1, "AAPL", 'B', 150.0, 100);
    engine.add_order(buy_order);
    
    // 添加卖单（价格匹配）
    Order sell_order(2, "AAPL", 'S', 149.0, 80);
    engine.add_order(sell_order);
    
    // 验证撮合结果
    const auto& trades = engine.get_trades();
    EXPECT_EQ(trades.size(), 1);
    
    const Trade& trade = trades[0];
    EXPECT_EQ(trade.buy_order_id, 1);
    EXPECT_EQ(trade.sell_order_id, 2);
    EXPECT_EQ(trade.symbol, "AAPL");
    EXPECT_EQ(trade.price, 149.0);  // 使用卖单价格
    EXPECT_EQ(trade.quantity, 80);
    
    // 验证订单状态
    const Order* buy_order_after = engine.get_order(1);
    const Order* sell_order_after = engine.get_order(2);
    
    ASSERT_NE(buy_order_after, nullptr);
    ASSERT_NE(sell_order_after, nullptr);
    
    EXPECT_EQ(buy_order_after->filled_quantity, 80);
    EXPECT_EQ(sell_order_after->filled_quantity, 80);
    EXPECT_TRUE(sell_order_after->is_fully_filled());
    EXPECT_FALSE(buy_order_after->is_fully_filled());
}

/**
 * 测试价格优先级
 */
TEST_F(MatchEngineComprehensiveTest, TestPricePriority) {
    SimpleMatchEngine engine;
    
    // 添加多个不同价格的买单
    engine.add_order(Order(1, "AAPL", 'B', 150.0, 100));
    engine.add_order(Order(2, "AAPL", 'B', 152.0, 100));  // 更高价格
    engine.add_order(Order(3, "AAPL", 'B', 148.0, 100));  // 更低价格
    
    // 验证最佳买价
    EXPECT_EQ(engine.get_best_bid("AAPL"), 152.0);
    
    // 添加卖单
    engine.add_order(Order(4, "AAPL", 'S', 151.0, 50));
    
    // 验证高价买单优先成交
    const auto& trades = engine.get_trades();
    EXPECT_EQ(trades.size(), 1);
    EXPECT_EQ(trades[0].buy_order_id, 2);  // 最高价买单
    EXPECT_EQ(trades[0].price, 151.0);
    EXPECT_EQ(trades[0].quantity, 50);
}

/**
 * 测试部分成交
 */
TEST_F(MatchEngineComprehensiveTest, TestPartialFill) {
    SimpleMatchEngine engine;
    
    // 添加大买单
    engine.add_order(Order(1, "AAPL", 'B', 150.0, 1000));
    
    // 添加小卖单
    engine.add_order(Order(2, "AAPL", 'S', 149.0, 300));
    engine.add_order(Order(3, "AAPL", 'S', 149.5, 200));
    
    // 验证成交记录
    const auto& trades = engine.get_trades();
    EXPECT_EQ(trades.size(), 2);
    
    // 验证买单部分成交
    const Order* buy_order = engine.get_order(1);
    ASSERT_NE(buy_order, nullptr);
    EXPECT_EQ(buy_order->filled_quantity, 500);  // 300 + 200
    EXPECT_FALSE(buy_order->is_fully_filled());
    EXPECT_EQ(buy_order->remaining_quantity(), 500);
}

/**
 * 测试订单取消
 */
TEST_F(MatchEngineComprehensiveTest, TestOrderCancellation) {
    SimpleMatchEngine engine;
    
    // 添加订单
    engine.add_order(Order(1, "AAPL", 'B', 150.0, 100));
    engine.add_order(Order(2, "AAPL", 'S', 155.0, 100));
    
    EXPECT_EQ(engine.get_buy_orders_count("AAPL"), 1);
    EXPECT_EQ(engine.get_sell_orders_count("AAPL"), 1);
    
    // 取消买单
    EXPECT_TRUE(engine.cancel_order(1));
    EXPECT_EQ(engine.get_buy_orders_count("AAPL"), 0);
    EXPECT_EQ(engine.get_sell_orders_count("AAPL"), 1);
    
    // 验证订单已被移除
    EXPECT_EQ(engine.get_order(1), nullptr);
    EXPECT_NE(engine.get_order(2), nullptr);
    
    // 取消不存在的订单
    EXPECT_FALSE(engine.cancel_order(999));
}

/**
 * 测试多品种订单处理
 */
TEST_F(MatchEngineComprehensiveTest, TestMultipleSymbols) {
    SimpleMatchEngine engine;
    
    // 添加不同品种的订单
    engine.add_order(Order(1, "AAPL", 'B', 150.0, 100));
    engine.add_order(Order(2, "GOOGL", 'B', 2500.0, 50));
    engine.add_order(Order(3, "MSFT", 'S', 300.0, 200));
    
    // 验证各品种的订单簿状态
    EXPECT_EQ(engine.get_buy_orders_count("AAPL"), 1);
    EXPECT_EQ(engine.get_buy_orders_count("GOOGL"), 1);
    EXPECT_EQ(engine.get_sell_orders_count("MSFT"), 1);
    
    EXPECT_EQ(engine.get_best_bid("AAPL"), 150.0);
    EXPECT_EQ(engine.get_best_bid("GOOGL"), 2500.0);
    EXPECT_EQ(engine.get_best_ask("MSFT"), 300.0);
    
    // 添加匹配订单
    engine.add_order(Order(4, "AAPL", 'S', 149.0, 80));
    
    // 验证只有AAPL发生成交
    const auto& trades = engine.get_trades();
    EXPECT_EQ(trades.size(), 1);
    EXPECT_EQ(trades[0].symbol, "AAPL");
}

/**
 * 测试价差计算
 */
TEST_F(MatchEngineComprehensiveTest, TestSpreadCalculation) {
    SimpleMatchEngine engine;
    
    // 无订单时价差为0
    EXPECT_EQ(engine.get_spread("AAPL"), 0.0);
    
    // 只有买单时价差为0
    engine.add_order(Order(1, "AAPL", 'B', 150.0, 100));
    EXPECT_EQ(engine.get_spread("AAPL"), 0.0);
    
    // 添加卖单后计算价差
    engine.add_order(Order(2, "AAPL", 'S', 155.0, 100));
    EXPECT_EQ(engine.get_spread("AAPL"), 5.0);  // 155 - 150
    
    // 添加更优价格的订单
    engine.add_order(Order(3, "AAPL", 'B', 152.0, 100));
    engine.add_order(Order(4, "AAPL", 'S', 153.0, 100));
    EXPECT_EQ(engine.get_spread("AAPL"), 1.0);  // 153 - 152
}

/**
 * 测试撮合引擎清理功能
 */
TEST_F(MatchEngineComprehensiveTest, TestEngineCleanup) {
    SimpleMatchEngine engine;
    
    // 添加一些订单和成交
    engine.add_order(Order(1, "AAPL", 'B', 150.0, 100));
    engine.add_order(Order(2, "AAPL", 'S', 149.0, 80));
    engine.add_order(Order(3, "GOOGL", 'B', 2500.0, 50));
    
    // 验证数据存在
    EXPECT_GT(engine.get_buy_orders_count("AAPL"), 0);
    EXPECT_GT(engine.get_buy_orders_count("GOOGL"), 0);
    EXPECT_GT(engine.get_trades().size(), 0);
    
    // 清理引擎
    engine.clear();
    
    // 验证所有数据被清理
    EXPECT_EQ(engine.get_buy_orders_count("AAPL"), 0);
    EXPECT_EQ(engine.get_sell_orders_count("AAPL"), 0);
    EXPECT_EQ(engine.get_buy_orders_count("GOOGL"), 0);
    EXPECT_EQ(engine.get_trades().size(), 0);
    EXPECT_EQ(engine.get_order(1), nullptr);
    EXPECT_EQ(engine.get_order(2), nullptr);
    EXPECT_EQ(engine.get_order(3), nullptr);
} 